package com.tanhua.autoconfig.template;

import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.tanhua.autoconfig.properties.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 短信发送接口
 */
@Slf4j
@Service
public class SmsTemplate {
    @Autowired
    private SmsProperties smsProperties;

    public SmsTemplate(SmsProperties smsProperties){
        this.smsProperties = smsProperties;
    }

    /**
     * 发送短信方法
     * @param mobile
     * @param code
     */
    public void sendSms(String mobile,String code) {

        try {
            //配置阿里云
            Config config = new Config()
                    // 您的AccessKey ID
                    .setAccessKeyId(smsProperties.getAccessKey())
                    // 您的AccessKey Secret
                    .setAccessKeySecret(smsProperties.getSecret())
                    // 访问的域名
                    .setEndpoint("dysmsapi.aliyuncs.com");

            com.aliyun.dysmsapi20170525.Client client = new com.aliyun.dysmsapi20170525.Client(config);

            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(mobile) //目标手机号
                    .setSignName(smsProperties.getSignName()) //签名名称
                    .setTemplateCode(smsProperties.getTemplateCode()) //短信模板code
                    .setTemplateParam("{\"code\":\""+code+"\"}"); //模板中变量替换

            //发送短信
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);

            SendSmsResponseBody body = sendSmsResponse.getBody();

            // code = OK 代表成功
            System.out.println(body.getCode() + "  " + body.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("发送短信验证码失败！" + mobile, e);
        }
    }

}